#!/usr/bin/env python3
"""
工具管理器：统一管理工具注册、执行和结果整合
"""

import logging
from typing import Dict, Any, Optional, List
from .registry import ToolRegistry
from .executor import ToolExecutor
from .tool import Tool, ToolResult

logger = logging.getLogger(__name__)


class ToolManager:
    """工具管理器"""

    def __init__(self):
        self.registry = ToolRegistry()
        self.executor = ToolExecutor(self.registry)
        self.conversation_context: List[Dict[str, Any]] = []

    def register_tool(
        self,
        tool: Tool,
        category: str = "general",
        tags: List[str] = None,
        enabled: bool = True,
    ) -> bool:
        """注册工具"""
        return self.registry.register_tool(tool, category, tags, enabled)

    def unregister_tool(self, tool_name: str) -> bool:
        """注销工具"""
        return self.registry.unregister_tool(tool_name)

    def execute_tool(
        self, tool_name: str, parameters: Dict[str, Any], context: Dict[str, Any] = None
    ) -> ToolResult:
        """执行单个工具"""
        return self.executor.execute_tool(tool_name, parameters, context)

    def execute_tool_chain(
        self, tool_chain: List[Dict[str, Any]], context: Dict[str, Any] = None
    ) -> List[ToolResult]:
        """执行工具链"""
        return self.executor.execute_tool_chain(tool_chain, context)

    def get_available_tools(self) -> List[str]:
        """获取可用工具列表"""
        return list(self.registry.get_enabled_tools().keys())

    def get_tool_schema(self, tool_name: str) -> Optional[Dict[str, Any]]:
        """获取工具调用模式"""
        return self.registry.get_tool_schema(tool_name)

    def get_tools_for_intent(self, intent: str) -> List[str]:
        """根据意图获取推荐工具"""
        # 检查是否有高德地图工具可用
        available_tools = self.registry.get_enabled_tools()

        if intent == "地理相关" and "amap_geocoding" in available_tools:
            return ["amap_geocoding", "amap_weather", "amap_poi"]
        elif intent == "天气查询" and "amap_weather" in available_tools:
            return ["amap_weather"]
        elif intent == "位置服务" and "amap_geocoding" in available_tools:
            return ["amap_geocoding", "amap_poi"]
        else:
            return self.registry.get_tools_for_intent(intent)

    def search_tools(self, keyword: str) -> List[str]:
        """搜索工具"""
        return self.registry.search_tools(keyword)

    def get_tool_info(self, tool_name: str) -> Optional[Dict[str, Any]]:
        """获取工具信息"""
        tool = self.registry.get_tool(tool_name)
        if tool:
            return tool.get_info()
        return None

    def get_all_tools_info(self) -> Dict[str, Dict[str, Any]]:
        """获取所有工具信息"""
        tools_info = {}
        for name, tool in self.registry.get_all_tools().items():
            tools_info[name] = tool.get_info()
        return tools_info

    def get_tool_stats(self) -> Dict[str, Any]:
        """获取工具统计信息"""
        registry_stats = self.registry.get_tool_stats()
        executor_stats = self.executor.get_tool_usage_stats()

        return {
            "registry": registry_stats,
            "executor": executor_stats,
            "total_executions": len(self.executor.execution_history),
        }

    def process_user_query(self, user_query: str, intent: str = None) -> Dict[str, Any]:
        """处理用户查询"""
        try:
            # 分析用户意图
            if not intent:
                intent = self._analyze_intent(user_query)

            # 选择工具
            recommended_tools = self.get_tools_for_intent(intent)

            # 生成工具调用计划
            execution_plan = self._generate_execution_plan(
                recommended_tools, user_query, intent
            )

            # 执行工具调用
            results = self.execute_tool_chain(
                execution_plan, {"user_query": user_query}
            )

            # 整合结果
            final_response = self._integrate_results(user_query, results)

            # 保存到对话上下文
            self.conversation_context.append(
                {
                    "user_query": user_query,
                    "intent": intent,
                    "tools_used": [plan["tool_name"] for plan in execution_plan],
                    "results": [result.to_dict() for result in results],
                    "final_response": final_response,
                    "timestamp": self._get_timestamp(),
                }
            )

            return {
                "success": True,
                "user_query": user_query,
                "intent": intent,
                "execution_plan": execution_plan,
                "results": [result.to_dict() for result in results],
                "final_response": final_response,
            }

        except Exception as e:
            logger.error(f"处理用户查询失败: {e}")
            return {"success": False, "error": str(e), "user_query": user_query}

    def _analyze_intent(self, user_query: str) -> str:
        """分析用户意图"""
        # 简化的意图分析
        intent_keywords = {
            "日志分析": ["日志", "log", "错误", "error", "异常", "exception"],
            "地理相关": ["地址", "位置", "地图", "天气", "导航", "周边"],
            "搜索查询": ["搜索", "查找", "如何", "怎么", "教程"],
            "天气查询": ["天气", "温度", "下雨", "晴天"],
            "位置服务": ["地址", "坐标", "位置", "导航"],
        }

        user_query_lower = user_query.lower()
        for intent, keywords in intent_keywords.items():
            if any(keyword in user_query_lower for keyword in keywords):
                return intent

        return "搜索查询"  # 默认意图

    def _generate_execution_plan(
        self, recommended_tools: List[str], user_query: str, intent: str
    ) -> List[Dict[str, Any]]:
        """生成工具执行计划"""
        execution_plan = []

        for tool_name in recommended_tools[:3]:  # 限制最多3个工具
            if tool_name in self.registry.get_enabled_tools():
                # 生成工具参数
                parameters = self._generate_tool_parameters(
                    tool_name, user_query, intent
                )

                execution_plan.append(
                    {"tool_name": tool_name, "parameters": parameters, "required": True}
                )

        return execution_plan

    def _generate_tool_parameters(
        self, tool_name: str, user_query: str, intent: str
    ) -> Dict[str, Any]:
        """生成工具参数"""
        # 简化的参数生成逻辑
        parameters = {}

        if tool_name == "amap_geocoding":
            # 从用户查询中提取地址信息
            parameters["address"] = self._extract_address_from_query(user_query)
            parameters["city"] = self._extract_city_from_query(user_query)

        elif tool_name == "amap_weather":
            parameters["city"] = self._extract_city_from_query(user_query) or "北京"
            parameters["extensions"] = "all"

        elif tool_name == "google_search":
            parameters["query"] = user_query
            parameters["num_results"] = 5

        elif tool_name == "stackoverflow_search":
            parameters["query"] = user_query
            parameters["tags"] = self._extract_tech_tags(user_query)

        elif tool_name == "github_search":
            parameters["query"] = user_query
            parameters["search_type"] = "code"

        elif tool_name == "parse_logs":
            parameters["log_data"] = "请提供日志数据"
            parameters["log_format"] = "auto"

        elif tool_name == "count_errors":
            parameters["parsed_logs"] = []  # 将在工具链中更新
            parameters["service_name"] = "all"

        elif tool_name == "analyze_time_patterns":
            parameters["parsed_logs"] = []  # 将在工具链中更新
            parameters["error_type"] = "ERROR"

        return parameters

    def _extract_address_from_query(self, user_query: str) -> str:
        """从查询中提取地址"""
        # 简化的地址提取逻辑
        import re

        address_patterns = [
            r"([^，。！？\s]+(?:市|区|县|镇|村|街道|路|号))",
            r"([^，。！？\s]+(?:天安门|故宫|长城|颐和园))",
        ]

        for pattern in address_patterns:
            match = re.search(pattern, user_query)
            if match:
                return match.group(1)

        return user_query

    def _extract_city_from_query(self, user_query: str) -> str:
        """从查询中提取城市"""
        cities = [
            "北京",
            "上海",
            "广州",
            "深圳",
            "杭州",
            "南京",
            "武汉",
            "成都",
            "西安",
            "重庆",
        ]

        for city in cities:
            if city in user_query:
                return city

        return ""

    def _extract_tech_tags(self, user_query: str) -> List[str]:
        """从查询中提取技术标签"""
        tech_keywords = {
            "python": ["python", "django", "flask", "pandas", "numpy"],
            "javascript": ["javascript", "nodejs", "react", "vue", "angular"],
            "java": ["java", "spring", "maven", "gradle"],
            "database": ["mysql", "postgresql", "mongodb", "redis", "sqlite"],
            "web": ["html", "css", "bootstrap", "jquery"],
            "mobile": ["android", "ios", "react-native", "flutter"],
        }

        tags = []
        user_query_lower = user_query.lower()

        for category, keywords in tech_keywords.items():
            if any(keyword in user_query_lower for keyword in keywords):
                tags.append(category)

        return tags[:3]  # 最多返回3个标签

    def _integrate_results(self, user_query: str, results: List[ToolResult]) -> str:
        """整合工具执行结果"""
        response_parts = []

        # 分析结果
        successful_results = [r for r in results if r.success]
        failed_results = [r for r in results if not r.success]

        if successful_results:
            response_parts.append("基于工具分析结果，我为您提供以下信息：\n")

            for result in successful_results:
                tool_name = result.metadata.get("tool_name", "未知工具")
                data = result.data

                if tool_name == "amap_geocoding":
                    response_parts.append(f"**地理编码结果**:\n")
                    if isinstance(data, dict) and "location" in data:
                        response_parts.append(f"- 坐标: {data['location']}")
                        response_parts.append(
                            f"- 地址: {data.get('formatted_address', '')}"
                        )

                elif tool_name == "amap_weather":
                    response_parts.append(f"**天气信息**:\n")
                    if isinstance(data, dict):
                        response_parts.append(f"- 城市: {data.get('city', '')}")
                        response_parts.append(f"- 温度: {data.get('temperature', '')}")
                        response_parts.append(f"- 天气: {data.get('weather', '')}")

                elif tool_name == "google_search":
                    response_parts.append(f"**搜索结果**:\n")
                    if isinstance(data, dict) and "results" in data:
                        for i, res in enumerate(data["results"][:3], 1):
                            response_parts.append(f"{i}. {res.get('title', '')}")
                            response_parts.append(f"   {res.get('link', '')}")

                response_parts.append("")

        if failed_results:
            response_parts.append("**执行过程中的问题**:\n")
            for result in failed_results:
                tool_name = result.metadata.get("tool_name", "未知工具")
                response_parts.append(f"- {tool_name}: {result.error}")
            response_parts.append("")

        if not response_parts:
            response_parts.append(
                "抱歉，我无法处理您的请求。请提供更多信息或尝试其他方式。"
            )

        return "\n".join(response_parts)

    def get_conversation_context(self) -> List[Dict[str, Any]]:
        """获取对话上下文"""
        return self.conversation_context.copy()

    def clear_conversation_context(self):
        """清空对话上下文"""
        self.conversation_context = []

    def _get_timestamp(self) -> str:
        """获取当前时间戳"""
        from datetime import datetime

        return datetime.now().isoformat()
